<template>
  <div class="article-list">
    <!-- 文章列表 -->

    <van-pull-refresh
      v-model="isreFreshLoading"
      @refresh="onRefresh"
      :success-text="refreshSuccessText"
      :success-duration="1500"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <ArticleItem
          v-for="(item, index) in list"
          :key="index"
          :article="item"
        ></ArticleItem>
        <!-- <van-cell
          v-for="(item, index) in list"
          :key="index"
          :title="item.title"
        /> -->
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/article'
import ArticleItem from '@/components/article-item'
export default {
  name: 'ArticleList',
  data () {
    return {
      list: [], // 存储列表数据的数组
      loading: false, // 控制加载中 loading 状态
      finished: false, // 控制数据加载结束的状态
      timestamp: null, // 请求获取下一页数据的时间戳
      error: false,
      isreFreshLoading: false,
      refreshSuccessText: '刷新成功'
    }
  },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  methods: {
    async onLoad () {
      try {
        // 1、请求获取数据
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })
        // if (Math.random() > 0.5) {
        //   JSON.parse("asdqwff");
        // }

        // console.log(data);
        // 2、把请求结果数据放到list 数组中
        const { results } = data.data
        this.list.push(...results)
        // 3、本次数据加载结束之后要把加载状态设置为结束
        this.loading = false
        // 4、判断数据是否全部加载完成
        if (results.length) {
          // 更新获取下一页数据的时间戳
          this.timestamp = data.data.pre_timestamp
        } else {
          // 没有数据了，将finished改为true，不再load加载更多
          this.finished = true
        }
      } catch (err) {
        // 展示错误提示示范
        this.error = true
        // 请求失败了，loading 也要关闭
        this.loading = false
      }
    },
    async onRefresh () {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now(),
          with_top: 1
        })
        const { results } = data.data
        this.list.unshift(...results)
        this.isreFreshLoading = false

        this.refreshSuccessText = `刷新了${results.length}条数据`
      } catch (err) {
        this.refreshSuccessText = '刷新失败'
      }
    }
  },
  created () {},
  components: {
    ArticleItem
  }
}
</script>

<style scoped lang="less">
.article-list {
  // 给每一个
  height: 79vh;
  overflow-y: auto;
}
</style>
